package com.sadhoc.sockets;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;

import com.sadhoc.router.PacketReceiver;
import com.sadhoc.router.pdu.HDPacket;
import com.sadhoc.router.util.Debug;

public class TCPReceiverHandler implements Runnable {
	
	private Socket cSocket			= null;
	private PacketReceiver receiver	= null;
	
	/*
	 * Constructor
	 */
    public TCPReceiverHandler(Socket cSocket, PacketReceiver receiver) {
    	
        this.cSocket = cSocket;
        this.receiver = receiver;
        
    }

    /*
	 * Handles the received TCP connection by waiting for a HDPacket object.
	 * When a HDPacket is received it adds it to the receiver queue.
	 * This loops while the socket is still connected, therefore we do 
	 * not need to constantly make new TCP sessions - which is why
	 * PacketSender tracks previously opened TCP sessions
	 */
	public void run() {
				
		Debug.printBasic("Accepted TCP session from " + cSocket.getRemoteSocketAddress() + ":" + cSocket.getPort());
		
		ObjectInputStream objIS = null;
		
		try {
			InputStream input = cSocket.getInputStream();
			objIS= new ObjectInputStream(input);
    	} catch (IOException e) {
    		e.printStackTrace();      		
	    }
			   		        	
		try {
			while(cSocket.isConnected()) {
				HDPacket p = (HDPacket) objIS.readObject();
				receiver.addQueue(p);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			objIS.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
      	
	}

}
